<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">

    <title>POWERSET</title>
    <style>
        {% include 'css/resetcss.css' %}
        body {
            background-color: #f8f8f8;
            height: 100vh;
            margin: 0;
            width: 100%;
            font-size: 0.8rem;
            display: flex;
            justify-content: center;
        }

        .form_div {
            /* 设置表单的样式 */
            display: flex;
            justify-content: space-between;
            flex-direction: column;
            right: 40%;
            width: 50%;
            height: 40%;
            padding: 0;
            border-radius: 4px;
            position: absolute;
            margin: 0 auto;
            top: 33%;
            left: 22%;
        }


        .tableBox {
            width: 100%;
            height: 20%;
        {#border: 1px solid black;#} position: absolute;
            top: 5%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
        }

        /* 设置表格样式 */
        table {
            border-collapse: collapse;
            width: 100%;
            font-family: Arial, sans-serif;
        }

        table th {
            padding: 8px;
            text-align: center;
            font-weight: bold;
        }

        table td {
            padding: 8px;
            text-align: center;
            vertical-align: middle;
            font-size: 0.8rem;
        }

        /* 设置表格列宽 */
        table th:nth-child(1) {
            width: 3%;
        }

        table th:nth-child(2) {
            width: 7%;
        }

        table th:nth-child(3) {
            width: 20%;
        }

        table th:nth-child(4) {
            width: 13%;
        }

        table th:nth-child(5) {
            width: 7%;
        }

        table th:nth-child(6) {
            width: 40%;
        }

        table th:nth-child(7) {
            width: 5%;
        }

        table th:nth-child(8) {
            width: 5%;
        }

        tr:nth-child(even) {
            background-color: rgba(76, 175, 80, 0.4);
        }

        textarea {
            width: 100%;
            height: 80%;
            padding: 10px;
            border: none;
            border-radius: 4px;
            box-sizing: border-box;
            margin-bottom: 20px;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
            word-break: break-all;
            font-family: 黑体, system-ui;
            resize: none; /* 禁止拖拽 */
        }

        /* 设置滚动条的样式 */
        textarea::-webkit-scrollbar {
            width: 10px;
        }

        /* 设置滚动条的轨道样式 */
        textarea::-webkit-scrollbar-track {
            background-color: #f1f1f1;
        }

        /* 设置滚动条的滑块样式 */
        textarea::-webkit-scrollbar-thumb {
            background-color: rgba(76, 175, 80, 0.4);
            border-radius: 5px;
        }

        /* 设置滚动条的滑块悬停样式 */
        textarea::-webkit-scrollbar-thumb:hover {
            background-color: rgba(76, 175, 80, 0.7);
        }

        .textarea-like {
            border: 1px solid #ccc;
            padding: 5px;
            width: 100%;
            height: 100px;
            overflow: auto;
            white-space: pre-wrap;
            word-wrap: break-word;
            word-break: break-all;
        }

        .textarea-like::before {
            content: attr(data-text);
            position: absolute;
            top: 0;
            left: 0;
            padding: 0.5em;
            white-space: pre-wrap;
            pointer-events: none;
            color: #999;
        }

        /* 设置表单输入框的样式 */
        input {
            width: 100%;
            padding: 15px;
            margin-bottom: 15px;
            border: none;
            border-radius: 4px;
            box-sizing: border-box;
            background-color: #fff;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        }

        /* 设置提交按钮的样式 */
        input[type="submit"],
        button[type="submit"],
        button[type="button"],
        input[type="button"] {
            position: relative;
            width: 100%;
            padding: 15px;
            border: none;
            border-radius: 4px;
            background-color: #4CAF50;
            color: #fff;
            cursor: pointer;
            margin-bottom: 15px;
        }

        /* 设置提交按钮的鼠标悬停样式 */
        input[type="submit"]:hover,
        button[type="submit"]:hover,
        button[type="button"]:hover,
        input[type="button"]:hover {
            background-color: #45a049;
        }
    </style>
    {% load static %}
    <script src="{% static 'js/alert.js' %}"></script>
    <script src="{% static 'js/validForm.js' %}"></script>
    <script src="{% static 'js/httpTool.js' %}"></script>
</head>
<body>
<div class="tableBox" id="tableBox">
</div>
<form class="form_div" id="my_form">
    {% csrf_token %}
    <label>
        <textarea name="powerset_text" rows="10" id="powerset_text" placeholder="请输入能力集"></textarea>
    </label>
    <label>
        <input type="text" id="sn" name="sn" maxlength="18" minlength="18" placeholder="设备SN">
    </label>
    <label>
        <input type="text" id="tp" name="tp" maxlength="9" minlength="9" placeholder="设备TP">
    </label>
    <label>
        <button type="button" onclick="deviceInfo()">查看设备</button>
    </label>
    <label>
        <button type="submit" id="submitButton">设 置</button>
    </label>
</form>
<script>

    function generateTable(deviceData) {
        let device = null;
        try {
            device = JSON.parse(deviceData)
            if (device == null) {
                return null
            }
        } catch (e) {
            return alert_error("设备信息返回有误")
        }
        // 移除旧的表格元素
        const oldTable = document.querySelector("table");
        if (oldTable) {
            oldTable.remove();
        }

        const boxDiv = document.getElementById("tableBox");
        // 创建表格元素
        const table = document.createElement("table");

        // 创建表头行
        const thead = document.createElement("thead");
        table.appendChild(thead);

        // 添加第一行表头
        const row1 = document.createElement("tr");
        thead.appendChild(row1);

        const headers1 = ["Id", "设备编号", "设备名称", "SN", "TP", "能力集", "", "平台"];

        for (let i = 0; i < headers1.length; i++) {
            let th = document.createElement("th");
            th.textContent = headers1[i];
            row1.appendChild(th);
        }

        // 添加第二行表头
        const row2 = document.createElement("tr");
        thead.appendChild(row2);

        const headers2 = [device.id, device.code, device.name, device.sn, device.tp_code, device.power_set, device.online_state, device.cloud_platform_code];
        console.log("headers2 --> ", headers2);
        for (let i = 0; i < headers2.length; i++) {
            let td = document.createElement("td");
            let content = headers2[i] || '---';
            if (content.length >= 300) {
                const divElement = document.createElement('div');
                divElement.classList.add('textarea-like')
                divElement.innerText = content
                td.appendChild(divElement);
            } else {
                td.textContent = content;
            }
            row2.appendChild(td);
        }
        // 将表格添加到页面中
        boxDiv.appendChild(table);
    }

    function getDeviceInfo() {
        let data = {
            sn: document.getElementById("sn").value,
            tp: document.getElementById("tp").value,
        }
        let url = '{% url 'deviceInfo' %}'
        post(url, data).then(api_resp => {
            if (api_resp.code === 0) {
                generateTable(api_resp.data)
            } else {
                alert_warn(api_resp.msg)
            }
        }).catch(error => {
            console.error('Error:', error);
            alert_error("系统繁忙,请稍后再试")
        });
    }


    function power_set() {
        let result = false
        let data = {
            sn: document.getElementById("sn").value,
            tp: document.getElementById("tp").value,
            power_set: document.getElementById("powerset_text").value,
        }
        console.log("data --> ", data);
        let url = '{% url 'devicePowerset' %}'
        return post(url, data).then(api_resp => {
            if (api_resp.code === 0) {
                alert_success(api_resp.msg)
                result = true
            } else {
                alert_warn(api_resp.msg)
            }
            return result
        }).catch(error => {
            console.error('Error:', error);
            alert_error("系统繁忙,请稍后再试")
            return result
        });
    }
</script>

<script>
    function deviceInfo() {
        if (onSubmitInputNotEmpty(["sn", "tp"])) {
            getDeviceInfo()
        }
    }
</script>
<!-- 处理提交⌛事件-->
<script>
    onFocusInputNotEmpty("sn")
    onFocusInputNotEmpty("tp")
    onFocusInputNotEmpty("powerset_text")
    // 获取表单元素
    const form = document.getElementById('my_form');

    // 表单提交事件处理函数
    function handleSubmit(event) {
        event.preventDefault(); // 阻止表单的默认提交行为
        submitForm()// 表单赋值
        // 执行表单校验逻辑
        if (validateForm()) {
            console.log("------> submit 事件")
            power_set().then(result => {
                console.log("------> ", result)
                if (result) {
                    getDeviceInfo()
                }
            })
        }
    }

    // 表单校验函数
    function validateForm() {
        // 执行表单校验逻辑，返回校验结果
        // 如果校验通过，返回 true；否则返回 false
        let validJsonResult = validJson("powerset_text")
        if (!validJsonResult) {
            alert_error("设备能力集格式有误")
        }
        return onSubmitInputNotEmpty(["sn", "tp", "powerset_text"]) && validJsonResult;
    }

    // 绑定提交按钮的点击事件
    const submitButton = document.getElementById('submitButton');
    submitButton.addEventListener('click', handleSubmit);

    function submitForm() {
        console.log("submit ... ")
    }
</script>
</body>
</html>

